package cn.edu.hrbcu.es.invigilatemanagerment.controller;

import cn.edu.hrbcu.es.invigilatemanagerment.pojo.Course;
import cn.edu.hrbcu.es.invigilatemanagerment.pojo.Examinfo;
import cn.edu.hrbcu.es.invigilatemanagerment.pojo.Speciality;
import cn.edu.hrbcu.es.invigilatemanagerment.service.ICourseService;
import cn.edu.hrbcu.es.invigilatemanagerment.service.IExamInfoService;
import cn.edu.hrbcu.es.invigilatemanagerment.service.ISpecialityService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/Course")
@Slf4j
public class CourseController {
    private final static String FILE_UPLOAD_PATH = "D:\\";

    @Autowired
    private ICourseService courseService;
    @Autowired
    private IExamInfoService examInfoService;
    @Autowired
    private ISpecialityService specialityService;

    @RequestMapping(value = {"/toAddCourse"})
    public String toAddCourse(Model model) {
        List<Speciality> specialities = specialityService.queryAllSpeciality();
        model.addAttribute("specialities",specialities);
        return "toaddcourse";
    }

    @RequestMapping(value = {"/toUpdateCourse"})
    public ModelAndView toUpdateCourse(Integer id) {
        List<Speciality> specialities = specialityService.queryAllSpeciality();
        Course course = courseService.queryCourseById(id);
        ModelAndView model = new ModelAndView("toupdatecourse");
        model.addObject("course", course);
        model.addObject("specialities", specialities);
        return model;
    }

    @RequestMapping("insertCourse")
    @ResponseBody
    public String insertCourse(String name,Integer specialityId,Double credit,Integer period,String note)
    {
        Course course = new Course(null,name,specialityId,credit,period,note);
        courseService.insertCourse(course);
        return "OK";
    }

    @RequestMapping("queryCourseById")
    @ResponseBody
    public Course queryCourseById(Integer id)
    {
        return courseService.queryCourseById(id);
    }

    @RequestMapping("deleteCourseById")
    @ResponseBody
    public String deleteCourseById(Integer id)
    {
        courseService.deleteCourseById(id);
        return "OK";
    }

    @RequestMapping("updateCourseById")
    @ResponseBody
    public String updateCourseById(Course course)
    {
        courseService.updateCourseById(course);
        return "OK";
    }

    /**
     * 金雪松修改了
     * @param model
     * @return
     */
    @RequestMapping("queryAllCourse")
    public String queryAllCourse(Model model,@RequestParam(value = "pageNow",defaultValue = "1") int pageNow,
                                 @RequestParam(value = "pageSize",defaultValue = "5") int pageSize)
    {
        int totalCount = courseService.queryTotalCount();
        int pageCount = (int)Math.ceil((double) totalCount / pageSize);
        List<Map<String,Object>> courses = new ArrayList<>();
        List<Course> courses_ = courseService.queryCourseByPage(pageNow,pageSize);
        if(!courses_.isEmpty() && courses_!=null)
        {
            for(Course course_ : courses_)
            {
                Map<String,Object> map = new HashMap<>();
                map.put("id",course_.getId());
                map.put("name",course_.getName());
                map.put("specialityname",specialityService.querySpecialityById(course_.getSpecialityId()).getName());
                map.put("credit",course_.getCredit());
                map.put("period",course_.getPeriod());
                map.put("note",course_.getNote());
                courses.add(map);
            }
        }
        model.addAttribute("courses",courses);
        model.addAttribute("pageNow", pageNow);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("pageCount", pageCount);
        return "course";
    }

    /**
     * 金雪松修改了
     * @param model
     * @return
     */
    @RequestMapping("selectCourse")
    public String selectCourse(Model model)
    {
        List<Course> courses = courseService.queryAllCourse();
        model.addAttribute("courses", courses);
        return "teachercourse";
    }

    @RequestMapping("queryCourseByName")
    @ResponseBody
    public List<Course> queryCourseByName(String name)
    {
        return courseService.queryCourseByName(name);
    }

    //    从服务器下载一个特定的文件
    @RequestMapping("/DownloadFile")
    @ResponseBody
    public void downloadFile(HttpServletResponse response) throws Exception{

        examInfoService.exportExcel();
        File readFile = new File("D:/考场信息表.xlsx");
        //字节流-用于读文件  这里只是demo用的非缓冲流。实际项目可以用BufferedInputStream。 此功能是读取图片，所以用的字节流。如果是文本的话可以用字符流效率高，具体类看下面注释
        //        BufferedReader bufferedReader = new BufferedReader(new FileReader(readFile));//字符流
        FileInputStream fileInputStream = new FileInputStream(readFile);//字节流
        //设置文件下载方式
        response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode("D:/考场信息表.xlsx","utf-8"));
        //获取servlet响应输出字节流
        //        PrintWriter writer = response.getWriter();//字符流
        ServletOutputStream outputStream = response.getOutputStream(); //字节流

        //流数据交换，每次交换10k数据大小 （1024k = 1m）
        byte[] bytes = new byte[1024*10];
        int read;
        do {
            read = fileInputStream.read(bytes);
            outputStream.write(bytes,0,read);
        }while (-1 != read);

        String charsetName = "UTF-8";
        //outputStream.write(trainingProgram.getContent().getBytes(charsetName));

        //关闭资源
        IOUtils.closeQuietly(fileInputStream);
        IOUtils.closeQuietly(outputStream);
    }

    //    将客户端上传的文件保存到服务器上
    @RequestMapping(value = "/UploadFile",method = RequestMethod.POST)
    @ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()){
            return "文件上传失败";
        }
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        System.out.println("fileName = " + fileName);
        //生成文件名称通用方法
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
        String newFileName = tempName.toString();
//        System.out.println("newFileName = " + newFileName);
        try {
            //保存文件
            byte[] bytes = file.getBytes();
            Path path = Paths.get(FILE_UPLOAD_PATH + fileName);
            Files.write(path,bytes);
            examInfoService.importExcel(path);
        }catch (IOException e){
            e.printStackTrace();
            return "文件上传失败";
        }
        return "上传成功";
    }

}
